#include "../server.hpp"


uint64_t conn_id = 0;

std::unordered_map<uint64_t, PtrConnection> _conns;
void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn)
{
    DEBUG_LOG("New Connection: %p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    std::string bufstr = buf->ReadAsString(buf->ReadableSize()).c_str();
    DEBUG_LOG("%s", bufstr.c_str());
    buf->ReadMove(buf->ReadableSize());
    std::string echostr = "Server echo: " + bufstr;
    conn->Send(&echostr[0], echostr.size());
    // conn->ShutDown();
}


void Acceptor(EventLoop *loop, Channel *lst_channel)
{
    int fd = lst_channel->Fd();
    int newfd = accept(fd, NULL, NULL);
    conn_id++;

    PtrConnection conn(new Connection(loop, conn_id, newfd));   
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));  
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));

    conn->EnableInactiveRelease(10);
    conn->Connected();  // 就绪初始化


    _conns.insert(std::make_pair(conn_id, conn));
}

void t1()
{
    srand(time(NULL));
    // Poller poller;
    EventLoop loop;
    Socket lst_sock;
    lst_sock.CreateServer(8787);
    Channel channel(&loop, lst_sock.Fd());    // 为 监听套接字 创建一个 Channel 进行事件管理 、添加修改移除
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));       // 设置监听套接字的可读监控，这里回调函数需要为 新连接创建 Channel 并添加监控

    channel.EnableRead();   // 监听套接字启动可读事件监控

    while(1)
    {
        loop.Start();
    }
    lst_sock.Close();
}


int main()
{
    t1();

    return 0;
}